package pers.kw.config.security;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;
import pers.kw.common.spring.utils.SpringUtils;
import pers.kw.config.oauth.context.MyParamValue;
import pers.kw.config.oauth.context.MyParamValueThreadLocal;
import pers.kw.contants.AuthParamName;
import pers.kw.enums.AuthUserTypeEnum;
import pers.kw.service.UserDetailStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义UserDetailService
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MyUserDetailsService.class);

    private static final List<GrantedAuthority> authorities = new ArrayList<>(2);

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("自定义UserDetailsService处理start...");
        MyParamValue paramValue = MyParamValueThreadLocal.getCurrent();
        log.info("获取自定义参数信息：{}", JSON.toJSONString(paramValue));

        String userType = paramValue.getAuthParameter(AuthParamName.USER_TYPE);
        if (StringUtils.isBlank(userType)) {
            throw new OAuth2Exception(AuthParamName.USER_TYPE + "不能为空");
        }
        if (!AuthUserTypeEnum.userTypeSet.contains(userType)) {
            throw new OAuth2Exception(AuthParamName.USER_TYPE + "错误");
        }
        AuthUserTypeEnum userTypeEnum = AuthUserTypeEnum.getEnumObjByCode(userType);
        if (userTypeEnum == null) {
            log.info("oauth服务，用户认证策略配置错误，{}:{}", AuthParamName.USER_TYPE, userType);
            throw new OAuth2Exception("认证系统异常");
        }

        try {
            UserDetailStrategy userDetailStrategy = (UserDetailStrategy) SpringUtils.getBean(Class.forName(userTypeEnum.getUserStrategy()));
            return userDetailStrategy.getUserInfoByMobile(userName,authorities);
        } catch (ClassNotFoundException e) {
            log.error("oauth服务，用户认证策略配置获取异常", e);
            throw new OAuth2Exception("认证系统异常");
        }
    }
}
